<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class store_controller extends PZ_Controller {
	public function __construct() {
		parent::__construct();
		$this->authfunctions = array('addlike','removelike','approve','create','manage');
	}

	protected function init(){
		$this->category_id =  $this->param("cid");
		if($this->category_id){
			$this->storecategory = load_db('store/storecategory')->getCategoryByid($this->category_id);

			$this->seo_title($this->storecategory['category_name']);
			$this->seo_keyword($this->storecategory['category_name']);
			$this->seo_description($this->storecategory['category_name']);
		}
	}
	
	public function beforeAction(){
		$result = parent::beforeAction();
		if($result){
			if(!$this->settings['store_open']){
				$this->message(lang('store_not_open','tip'), lang('store_not_open_tip','tip'));
				$result = false;
			}
		}
		return $result;
	}

	public function index(){
		$this->load_seo('store');
		$storedb = load_db('store');
		$storecategories = load_db('store/storecategory')->getAllCategories();
		$topicapi = load_api('topic');
		foreach ($storecategories as $key=>$cate){
			if($cate['topics']){
				$topics = explode(',', $cate['topics']);
				$storecategories[$key]['topics'] = $topicapi->searchFull(array('topics'=>$topics),1,20);
				$storecategories[$key]['topicnum'] = array_length($storecategories[$key]['topics']);
				$storecategories[$key]['topicsTop'] = array_slice($storecategories[$key]['topics'],0, 4);
				$storecategories[$key]['topicsNormal'] = array_slice($storecategories[$key]['topics'],4);
			}
			$storecategories[$key]['storenum'] = $storedb->findCount(array('category_id'=>$cate['category_id']));
		}
		$this->storecates = $storecategories;
		$this->output("store/index");
	}

	public function listing(){
		$num_per_page = 10;
		$category_id =  $this->param("cid");
		$sort =  $this->param("sort",'dlike');
		$args = array();
		if($category_id){
			$this->category_id = $conditions['category_id'] = $args['cid'] = $category_id;
		}

		if($sort){
			$this->sort = $args['sort'] = $sort;
		}

		if($sort=='dtime'){
			$sort = " ptx_store.create_time DESC ";
		}elseif($sort=='atime'){
			$sort = " ptx_store.create_time ASC ";
		}elseif($sort=='dlike'){
			$sort = " ptx_store.total_like DESC ";
		}
		$this->page = $this->param('page','1');
		$stores = load_db("store")->search($conditions,$this->page,$num_per_page,null,$sort);
		$pager = &load_class('Pager', 'core');
		$this->pages = $pager->createPages('store/listing',$args);
		if($stores){
			$stores = load_api('store')->preparestores($stores);
			if($this->islogin){
				$favdb = load_db("store/favstore");
				foreach ($stores as $key=>$store){
					$stores[$key]['liked'] = $favdb->find_one(array('user_id'=>$this->cuser['uid'],'store_id'=>$store['store_id']));
				}
			}
		}
		$topicapi = load_api('topic');
		if($this->storecategory['topics']){
			$topics = explode(',', $this->storecategory['topics']);
			$topics = $topicapi->searchFull(array('topics'=>$topics),1,3,false);
			//$this->topics = rand_pop($topics);
			$this->tpl_waterfall = $this->render('waterfall/storetopic',array('topics'=>$topics));
		}

		$this->stores = $stores;
		$this->output("store/listing");
	}

	public function shares(){
		$api = load_api('setting');
		$setting = $api->getSetting('layoutpin');
		$pagesize = $setting['uipin_numperpage']?$setting['uipin_numperpage']:15;
		$data['page'] = $this->param('page','1');

		if($data['page']==1){
		}
		$this->category_id =  $this->param("cid");
		$args = array("page"=>"2","wf"=>"1","cid"=>$this->category_id);

		$data['nextpage_url'] = site_url_param('store/shares',$args);
		$followings_sql = load_db('store')->findAllSql(array('category_id'=>$this->category_id),null," store_id ");
		$conditions['store_id_in']['store_id'] = array($followings_sql);

		$shareapi = load_api('share');
		$shares = $shareapi->search($conditions,$data['page'],$pagesize,' ptx_share.create_time DESC ');
		$shares = $shareapi->prepareShares($shares);
		if($setting['uipin_ads']){
			$shares = $shareapi->add_ads($shares);
		}
		$pager = &load_class('Pager', 'core');
		$data['pages'] = $pager->createPages('store/shares',$args);
		$pageData = $pager->getPager();
		$data['numbershares'] = $pageData['total_count'];
		$data['tpl_waterfall'] = $this->render('waterfall/pin',array('shares'=>$shares));
		$data['pinsetting'] = $setting;
		if($data['page']==1){
			if($this->storecategory['topics']){
				$topics = explode(',', $this->storecategory['topics']);
				$topics = load_api('topic')->searchFull(array('topics'=>$topics),1,3,false);
				$this->topics_waterfall = $this->render('waterfall/storetopic',array('topics'=>$topics));
			}
		}
		$this->output("store/shares",$data,($data['page']==1)?true:false);
	}

	public function topics(){
		$category_id =  $this->param("cid");
		$storedb = load_db('store');
		$topicapi = load_api('topic');
		if($this->storecategory['topics']){
			$topics = explode(',', $this->storecategory['topics']);
			$topics = $topicapi->searchFull(array('topics'=>$topics),1,20,false);
		}
		$this->storenum = $storedb->findCount(array('category_id'=>$this->storecategory['category_id']));
		$this->tpl_waterfall = $this->render('waterfall/storetopic',array('topics'=>$topics));
		
		$this->suggestactivities = load_api('store')->getsuggestactivities();
		$this->output("store/topics");
	}

	public function create(){
		$params=array('category_id'=>'','store_name'=>'0','province'=>'','city'=>'','address'=>'','phone1'=>'','store_desc'=>'');
		$act=$this->param('act');
		$data = array();
		if($act=='save'){
			foreach ($params as $key=>$default){
				$data[$key] = $this->param($key,$default);
			}
			$data['poster_id'] = $this->cuser['uid'];
			$data['poster_nickname'] = $this->cuser['nickname'];
			$sg = &load_class('Segment');
			$sgresult = $sg->getDbData($data['store_name']);
			$data['keyword'] = $sgresult['keyword'];
			$data['keyword_search'] = $sgresult['keywordSearch'];
			$storeid = load_db('store')->add_one($data);
			$this->ajax_success_response(array('url'=>site_url('store/review?storeid='.$storeid)), lang('operate_success','admin'));
			return;
		}else{
			$this->output("store/create");
		}
	}

	public function detail(){
		if($storeid =  $this->param("storeid")){
			$this->store = load_api("store")->getStoreById($storeid);
		}
		if(!$this->store){
			$this->redirect(site_url('store/index'), lang('404_error_content','tip'));
			return;
		}
		$this->liked = load_db("store/favstore")->find_one(array('user_id'=>$this->cuser['uid'],'store_id'=>$this->store['store_id']));

		$this->seo_title($this->store['store_name']);
		$this->seo_keyword($this->store['keyword']);
		$this->seo_description($this->store['store_desc']);
		load_db("store")->add_visit($this->store['store_id']);
		$this->output('store/detail');
	}

	public function comment(){
		if($storeid =  $this->param("storeid")){
			$this->store = load_api("store")->getStoreById($storeid);
		}
		if(!$this->store){
			$this->redirect(site_url('store/index'), lang('404_error_content','tip'));
			return;
		}
		$this->liked = load_db("store/favstore")->find_one(array('user_id'=>$this->cuser['uid'],'store_id'=>$this->store['store_id']));

		$this->seo_title($this->store['store_name']);
		$this->seo_keyword($this->store['keyword']);
		$this->seo_description($this->store['store_desc']);
		load_db("store")->add_visit($this->store['store_id']);
		$this->output('store/comment');
	}

	public function approve(){
		if($storeid =  $this->param("storeid")){
			$this->store = load_api("store")->getStoreById($storeid);
		}
		if(!$this->store){
			$this->redirect(site_url('store/index'), lang('404_error_content','tip'));
			return;
		}
		$act = $this->param('act');
		if($act=='save'){
			$params=array('category_id'=>'','store_name'=>'0','province'=>'','city'=>'','address'=>'','phone1'=>'','phone2'=>'','phone3'=>'','keyword'=>'','store_desc'=>'');
			foreach ($params as $key=>$default){
				$data[$key] = $this->param($key,$default);
			}
			if($data['keyword']){
				$data['keyword'] = $data['keyword'];
				$data['keyword_search'] = encodekeywords(explode(',', $data['keyword']));
			}
			if(load_db('store')->updateStoreByid($storeid,$data)){
					
				$cover = $this->param('cover');
				if($this->param('bannerchanged')=='true'&&$cover&&filename_check($cover)){
					$cover = BASEPATH.$cover;
					if(file_exists($cover)){
						$res = load_api('store')->storeres($storeid);
						$dirpath = BASEPATH.$res['dir'];
						(!is_dir($dirpath))&&@mkdir($dirpath,0777,true);
						file_exists($dirpath.$res['avatar']) && unlink($dirpath.$res['avatar']);
						@copy($cover, $dirpath.$res['avatar']);
					}
				}
				$applydb = load_db('misc/apply');
				if(!$applydb->find_one(array('user_id'=>$this->cuser['uid'],'rel_id'=>$storeid))){
					$applydb->add_storeapply($this->cuser['uid'],$data['category_id'],$storeid,$data['store_desc']);
				}
				$this->ajax_success_response(array('url'=>site_url('store/review?storeid='.$storeid)), lang('200_operatesuccess','tip'));
				return;
			}
			$this->ajax_failed_response(lang('500_operatefaild','tip'));
			return;
		}else{
			$this->output("store/approve");
			return;
		}
	}

	private function output_pin($action,$order,$conditions=array()){
		if($storeid =  $this->param("storeid")){
			$this->store = load_api("store")->getStoreById($storeid);
		}
		if(!$this->store){
			$this->redirect(site_url('store/index'), lang('404_error_content','tip'));
			return;
		}

		$api = load_api('setting');
		$setting = $api->getSetting('layoutpin');
		$pagesize = $setting['uipin_numperpage']?$setting['uipin_numperpage']:15;
		$numbershowpage = $setting['uipin_numbershowpage']?$setting['uipin_numbershowpage']:0;
		$page = $this->param('page','1');
		$wpage = $this->param('wpage');
		$args = array("page"=>"2","wf"=>"1","storeid"=>$this->store['store_id']);
		if($wpage&&$numbershowpage){
			$data['page'] = ($wpage-1)*$numbershowpage+$page;
			$args['wpage'] = $data['wpage'] = $wpage;
		}else{
			$data['page'] = $page;
		}
		$data['showpage'] = (($numbershowpage)&&($data['page']%$numbershowpage==0))?'1':'0';
		

		if($data['page']==1){
			load_db("store")->add_visit($this->store['store_id']);
			$this->liked = load_db("store/favstore")->find_one(array('user_id'=>$this->cuser['uid'],'store_id'=>$this->store['store_id']));

			$this->seo_title($this->store['store_name']);
			$this->seo_keyword($this->store['keyword']);
			$this->seo_description($this->store['store_desc']);
		}

		$data['nextpage_url'] = site_url_param('store/'.$action,$args);
		$shareapi = load_api('share');
		$shares = $shareapi->search(array('channel'=>$action,'store_id'=>$this->store['store_id']),$data['page'],$pagesize,$order);
		$shares = $shareapi->prepareShares($shares);
		if($setting['uipin_ads']){
			$shares = $shareapi->add_ads($shares);
		}
		$pager = &load_class('Pager', 'core');
		unset($args['wf']);
		$data['pages'] = $pager->createPages('store/'.$action,$args);
		$pageData = $pager->getPager();
		$data['numbershares'] = $pageData['total_count'];
		unset($args['page']);
		$data['wpages'] = $pager->createCustomPages('store/'.$action,$args,'wpage',$pagesize*$numbershowpage);
		$data['tpl_waterfall'] = $this->render('waterfall/pin',array('shares'=>$shares,'showpage'=>$data['showpage']));
		$data['pinsetting'] = $setting;
		$this->output("store/show",$data,($data['page']==1)?true:false);
	}

	public function activity(){
		$this->output_pin('activity', " ptx_share.create_time DESC ");
	}

	public function review(){
		$this->output_pin('review', " ptx_share.create_time DESC ");
	}

	public function product(){
		$this->output_pin('product', " ptx_share.create_time DESC ");
	}

	public function addlike(){
		if($storeid =  $this->param("storeid")){
			$this->store = load_db("store")->find_one(array('store_id'=>$storeid));
		}

		if(!$this->store){
			$this->redirect(site_url('store/listing'), lang('404_error_content','tip'));
			return;
		}
		if($this->store){
			$data['user_id'] = $this->cuser['uid'];
			$data['store_id'] = $this->store['store_id'];
			$result = load_db("store/favstore")->add_one($data);
			if($result){
				load_db("store")->add_like($this->store['store_id']);
				$this->ajax_success_response(null, 'success');
			}else{
				$this->ajax_failed_response('like_already');
			}
		}

	}

	public function removelike(){
		if($storeid =  $this->param("storeid")){
			$this->store = load_db("store")->find_one(array('store_id'=>$storeid));
		}

		if(!$this->store){
			$this->redirect(site_url('store/listing'), lang('404_error_content','tip'));
			return;
		}
		if($this->store){
			$data['user_id'] = $this->cuser['uid'];
			$data['store_id'] = $this->store['store_id'];
			if(load_db("store/favstore")->find_one($data)){
				$result = load_db("store/favstore")->delete($data);
				load_db("store")->remove_like($this->store['store_id']);
				$this->ajax_success_response(null, 'success');
			}else{
				$this->ajax_failed_response('like_already');
			}
		}

	}

	public function manage(){
		if($storeid =  $this->param("storeid")){
			$this->store = load_api("store")->getStoreById($storeid);
		}
		if(!$this->store){
			$this->redirect(site_url('store/index'), lang('404_error_content','tip'));
			return;
		}
		if(!$this->isadmin&&!$this->iseditor&&$this->store['user_id']!=$this->cuser['uid']){
			$this->redirect(site_url('store/index'), lang('illegal_operation','tip'));
			return;
		}
		$this->seo_title($this->store['store_name']);
		$this->seo_keyword($this->store['keyword']);
		$this->seo_description($this->store['store_desc']);
		$act = $this->param('act');
		if($act=='save'){
			$params=array('category_id'=>'','store_name'=>'0','province'=>'','city'=>'','address'=>'','phone1'=>'','phone2'=>'','phone3'=>'','keyword'=>'','store_desc'=>'');
			foreach ($params as $key=>$default){
				$data[$key] = $this->param($key,$default);
			}
			if($data['keyword']){
				$data['keyword'] = $data['keyword'];
				$data['keyword_search'] = encodekeywords(explode(',', $data['keyword']));
			}
			if(load_db('store')->updateStoreByid($storeid,$data)){
					
				$cover = $this->param('cover');
				if($this->param('bannerchanged')=='true'&&$cover&&filename_check($cover)){
					$cover = BASEPATH.$cover;
					if(file_exists($cover)){
						$res = load_api('store')->storeres($storeid);
						$dirpath = BASEPATH.$res['dir'];
						(!is_dir($dirpath))&&@mkdir($dirpath,0777,true);
						file_exists($dirpath.$res['avatar']) && unlink($dirpath.$res['avatar']);
						@copy($cover, $dirpath.$res['avatar']);
					}
				}
				$this->ajax_success_response(array('url'=>site_url('store/manage?storeid='.$storeid)), lang('200_operatesuccess','tip'));
				return;
			}
			$this->ajax_failed_response(lang('500_operatefaild','tip'));
			return;
		}else{
			$this->output("store/manage");
			return;
		}
	}
}
